package slowka;

import java.awt.event.*;
import java.beans.*;
import java.io.*;
import java.util.*;
import javax.swing.*;
import javax.swing.filechooser.FileNameExtensionFilter;

public class MainWindow extends javax.swing.JFrame {
    /** Creates new form MainWindow */
    public MainWindow() {
        initComponents();

        restart();
    }

    private void refreshMenuItemsLabels() {
        // tbd refactor this!
        About.setText(resourceBundle.getString("ABOUT"));
        OptionsMenu.setText(resourceBundle.getString("OPTIONS"));
        EnglishLanguageMenuItem.setText(resourceBundle.getString("ENGLISH"));
        FileMenu.setText(resourceBundle.getString("FILE"));
        LanguageMenu.setText(resourceBundle.getString("LANGUAGE"));
        NewFileMenuItem.setText(resourceBundle.getString("NEW"));
        OpenFileMenuItem.setText(resourceBundle.getString("OPEN"));
        PolishLanguageMenuItem.setText(resourceBundle.getString("POLISH"));
        SaveAsFileMenuItem.setText(resourceBundle.getString("SAVE_AS..."));
        SaveFileMenuItem.setText(resourceBundle.getString("SAVE"));
    }

    @SuppressWarnings("unchecked")
    private void initComponents() {//GEN-BEGIN:initComponents

        openErrorDialog = new javax.swing.JDialog();
        dialogMessage = new javax.swing.JLabel();
        jButton1 = new javax.swing.JButton();
        TabbedPane = new javax.swing.JTabbedPane();
        jMenuBar1 = new javax.swing.JMenuBar();
        FileMenu = new javax.swing.JMenu();
        NewFileMenuItem = new javax.swing.JMenuItem();
        OpenFileMenuItem = new javax.swing.JMenuItem();
        SaveFileMenuItem = new javax.swing.JMenuItem();
        SaveAsFileMenuItem = new javax.swing.JMenuItem();
        OptionsMenu = new javax.swing.JMenu();
        LanguageMenu = new javax.swing.JMenu();
        EnglishLanguageMenuItem = new javax.swing.JMenuItem();
        PolishLanguageMenuItem = new javax.swing.JMenuItem();
        About = new javax.swing.JMenuItem();

        openErrorDialog.setTitle("File open error");
        openErrorDialog.setMinimumSize(new java.awt.Dimension(200, 120));

        dialogMessage.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
        dialogMessage.setText("Failed to load file!");

        jButton1.setText("OK");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout openErrorDialogLayout = new javax.swing.GroupLayout(openErrorDialog.getContentPane());
        openErrorDialog.getContentPane().setLayout(openErrorDialogLayout);
        openErrorDialogLayout.setHorizontalGroup(
            openErrorDialogLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(openErrorDialogLayout.createSequentialGroup()
                .addGroup(openErrorDialogLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(openErrorDialogLayout.createSequentialGroup()
                        .addGap(34, 34, 34)
                        .addComponent(dialogMessage))
                    .addGroup(openErrorDialogLayout.createSequentialGroup()
                        .addGap(67, 67, 67)
                        .addComponent(jButton1)))
                .addContainerGap(30, Short.MAX_VALUE))
        );
        openErrorDialogLayout.setVerticalGroup(
            openErrorDialogLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(openErrorDialogLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(dialogMessage)
                .addGap(18, 18, 18)
                .addComponent(jButton1)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("Słówka");

        FileMenu.setText(resourceBundle.getString("FILE")); // NOI18N

        NewFileMenuItem.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_N, java.awt.event.InputEvent.CTRL_MASK));
        NewFileMenuItem.setLabel(resourceBundle.getString("NEW")); // NOI18N
        NewFileMenuItem.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                NewFileMenuItemActionPerformed(evt);
            }
        });
        FileMenu.add(NewFileMenuItem);

        OpenFileMenuItem.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_O, java.awt.event.InputEvent.CTRL_MASK));
        OpenFileMenuItem.setText(resourceBundle.getString("OPEN")); // NOI18N
        OpenFileMenuItem.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                OpenFileMenuItemActionPerformed(evt);
            }
        });
        FileMenu.add(OpenFileMenuItem);

        SaveFileMenuItem.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_S, java.awt.event.InputEvent.CTRL_MASK));
        SaveFileMenuItem.setText(resourceBundle.getString("SAVE")); // NOI18N
        SaveFileMenuItem.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                SaveFileMenuItemActionPerformed(evt);
            }
        });
        FileMenu.add(SaveFileMenuItem);

        SaveAsFileMenuItem.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_S, java.awt.event.InputEvent.SHIFT_MASK | java.awt.event.InputEvent.CTRL_MASK));
        SaveAsFileMenuItem.setText(resourceBundle.getString("SAVE_AS...")); // NOI18N
        SaveAsFileMenuItem.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                SaveAsFileMenuItemActionPerformed(evt);
            }
        });
        FileMenu.add(SaveAsFileMenuItem);

        jMenuBar1.add(FileMenu);

        OptionsMenu.setText(resourceBundle.getString("OPTIONS")); // NOI18N

        LanguageMenu.setText(resourceBundle.getString("LANGUAGE")); // NOI18N

        EnglishLanguageMenuItem.setText(resourceBundle.getString("ENGLISH")); // NOI18N
        EnglishLanguageMenuItem.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                EnglishLanguageMenuItemActionPerformed(evt);
            }
        });
        LanguageMenu.add(EnglishLanguageMenuItem);

        PolishLanguageMenuItem.setLabel(resourceBundle.getString("POLISH"));
        PolishLanguageMenuItem.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                PolishLanguageMenuItemActionPerformed(evt);
            }
        });
        LanguageMenu.add(PolishLanguageMenuItem);

        OptionsMenu.add(LanguageMenu);

        About.setText(resourceBundle.getString("ABOUT")); // NOI18N
        OptionsMenu.add(About);

        jMenuBar1.add(OptionsMenu);

        setJMenuBar(jMenuBar1);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(TabbedPane, javax.swing.GroupLayout.DEFAULT_SIZE, 293, Short.MAX_VALUE)
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(TabbedPane, javax.swing.GroupLayout.DEFAULT_SIZE, 322, Short.MAX_VALUE)
                .addContainerGap())
        );

        pack();
    }//GEN-END:initComponents

    private void PolishLanguageMenuItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_PolishLanguageMenuItemActionPerformed
        resourceBundle = ResourceBundle.getBundle("slowka/ResourceBundle_pl_PL");
        reloadObjects();
}//GEN-LAST:event_PolishLanguageMenuItemActionPerformed
    private void EnglishLanguageMenuItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_EnglishLanguageMenuItemActionPerformed
        resourceBundle = ResourceBundle.getBundle("slowka/ResourceBundle_en_US");
        reloadObjects();
        jMenuBar1.repaint();
}//GEN-LAST:event_EnglishLanguageMenuItemActionPerformed

    private void SaveAsFileMenuItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_SaveAsFileMenuItemActionPerformed
        saveToDisk(chooseFile(false));
}//GEN-LAST:event_SaveAsFileMenuItemActionPerformed
    private void SaveFileMenuItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_SaveFileMenuItemActionPerformed
        saveToDisk(thisFile);
}//GEN-LAST:event_SaveFileMenuItemActionPerformed
    private void OpenFileMenuItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_OpenFileMenuItemActionPerformed
        XMLDecoder Decoder;
        thisFile = chooseFile(true);

        if(thisFile != null) {
            clear();
            try {
                Decoder = new XMLDecoder(new FileInputStream(thisFile));
                appendPanels((List<Suite>) Decoder.readObject());
            } catch (Exception ex) {
                openErrorDialog.setVisible(true);
                restart();
            }
        }
}//GEN-LAST:event_OpenFileMenuItemActionPerformed
    private void NewFileMenuItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_NewFileMenuItemActionPerformed
        restart();
}//GEN-LAST:event_NewFileMenuItemActionPerformed

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        openErrorDialog.setVisible(false);
    }//GEN-LAST:event_jButton1ActionPerformed

    /**
    * @param args the command line arguments
    */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new MainWindow().setVisible(true);
            }
        });
    }

    private void createTestPnanel() {
        testPanel = new TestPanel(getSuites(), new ActionListener() {

            public void actionPerformed(ActionEvent e) {
                if(e.getActionCommand().contentEquals("disappear"))
                    setVisible(false);
                 if(e.getActionCommand().contentEquals("appear")) {
                    readSuitesFromTables();
                    setVisible(true);
                 }
                 if(e.getActionCommand().contentEquals("reload suites")) {
                    readSuitesFromTables();
                    testPanel.setSuites(getSuites());
                 }
            }
        }, resourceBundle);
    }
    private void reloadObjects() {
        readSuitesFromTables();
        List<Suite> tmp = getSuites();
        clear();
        refreshMenuItemsLabels();
        appendPanels(tmp);
    }
    private void clear() {
        TabbedPane.removeAll();
        suitePanels.clear();
    }

    /** Appends suites and dreates panels for them
     * @param suites suites to be appended
     */
    private void appendPanels(List<Suite> suites) {
        for(Suite s : suites)
            suitePanels.add(new SuitePanel(s, resourceBundle));

        for(SuitePanel sp : suitePanels)
            TabbedPane.add(sp.getName(), sp);

        createTestPnanel();
        TabbedPane.add(resourceBundle.getString("TEST"), testPanel);
    }

    /** Redraws window with default panels */
    private void restart() {
        clear();

        LinkedList<Suite> suites = new LinkedList<Suite>();
        suites.add(new Suite("WORDS", resourceBundle.getString("POLISH"), resourceBundle.getString("ENGLISH")));
        suites.add(new Suite("PHRASES", resourceBundle.getString("POLISH"), resourceBundle.getString("ENGLISH")));
        suites.add(new Suite("IDIOMS", resourceBundle.getString("POLISH"), resourceBundle.getString("ENGLISH")));

        appendPanels(suites);
    }

    private void readSuitesFromTables() {
        for(SuitePanel s : suitePanels)
            s.loadFromTable();
    }
    private List<Suite> getSuites() {
        List<Suite> suites = new LinkedList<Suite>();
        for(SuitePanel sp : suitePanels)
            suites.add(sp.getWordsSuite());
        return suites;
    }

    private File chooseFile(boolean willOpen) {
        int returnVal;
        JFileChooser fc = new JFileChooser();

        fc.setFileSelectionMode(JFileChooser.FILES_ONLY);
        fc.setFileFilter(new FileNameExtensionFilter(resourceBundle.getString("XML_FILES"), "xml"));

        if(willOpen == true) {
            fc.setApproveButtonText(resourceBundle.getString("OPEN"));
            returnVal = fc.showOpenDialog(this);
        }
        else {
            fc.setApproveButtonText(resourceBundle.getString("SAVE"));
            returnVal = fc.showSaveDialog(About);
        }

        if (returnVal == JFileChooser.APPROVE_OPTION) {
            File file = fc.getSelectedFile();
            if(!file.getName().substring(file.getName().length()-4).contentEquals(".xml"))
                file = new File(file.getAbsoluteFile().toString().concat(".xml"));
            return file;
        }
        else
            return null;
    }

    private void saveToDisk(File chooseFile) {
        readSuitesFromTables();
        XMLEncoder Encoder;

        if(chooseFile != null) {
            try {
                Encoder = new XMLEncoder(new FileOutputStream(chooseFile));
                Suite.extractPersistanceDelegates(Encoder);
                Encoder.writeObject(getSuites());
                Encoder.close();
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JMenuItem About;
    private javax.swing.JMenuItem EnglishLanguageMenuItem;
    private javax.swing.JMenu FileMenu;
    private javax.swing.JMenu LanguageMenu;
    private javax.swing.JMenuItem NewFileMenuItem;
    private javax.swing.JMenuItem OpenFileMenuItem;
    private javax.swing.JMenu OptionsMenu;
    private javax.swing.JMenuItem PolishLanguageMenuItem;
    private javax.swing.JMenuItem SaveAsFileMenuItem;
    private javax.swing.JMenuItem SaveFileMenuItem;
    private javax.swing.JTabbedPane TabbedPane;
    private javax.swing.JLabel dialogMessage;
    private javax.swing.JButton jButton1;
    private javax.swing.JMenuBar jMenuBar1;
    private javax.swing.JDialog openErrorDialog;
    // End of variables declaration//GEN-END:variables

    private ResourceBundle resourceBundle = ResourceBundle.getBundle("slowka/ResourceBundle_pl_PL");

    List<SuitePanel> suitePanels = new LinkedList<SuitePanel>();
    TestPanel testPanel;
    File thisFile;
}
